package hk.m4s.lr.repair.test.ui.user;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.InputStream;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import framework.common.Constant;
import framework.common.alertview.AlertView;
import framework.common.alertview.OnItemClickListener;
import framework.common.baseui.UeBaseActivity;
import framework.common.rsa.Base64Utils;
import framework.common.rsa.RSAUtils;
import framework.common.takephoto.CustomHelper;
import framework.common.zanetwork.core.ResponseCallback;
import framework.common.zanetwork.core.UploadCallback;
import framework.common.zanetwork.core.UploadHelper;
import framework.utils.SharedPreferencesUtils;
import hk.m4s.lr.repair.test.R;
import hk.m4s.lr.repair.test.model.UserinfoModel;
import hk.m4s.lr.repair.test.service.user.MyService;
import hk.m4s.lr.repair.test.utils.ToastUtil;
import hk.m4s.lr.repair.test.views.CornersTransform;
import okhttp3.Response;

/**
 * Created by qi.wang on 2017/3/21.
 * 个人信息修改
 */

public class UserEditActivity extends UeBaseActivity implements OnItemClickListener {
    private RelativeLayout click_head, click_phone;
    private LinearLayout click_get_address;
    private ImageView user_head;
    private ArrayList<TImage> imgList;
    private Context mContext;
    private EditText user_name, user_nick;
    private TextView user_phone, user_address_name, home_send_order,userNumber,user_compay_name;
    private static final int REQUEST_CODE_EDIT_ADDRESS = 3;
    private static final int REQUEST_CODE_EDIT_PHONE = 5;
    private AlertView mAlertViewExt;
    private EditText etName;
    private InputMethodManager imm;
    private String logo = "", name = "", nickname = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        baseSetContentView(R.layout.activity_user_edit);
        mContext = this;
        hiddenFooter();
        hiddenNewMessage();
        showGoBackBtn();
        setTitleText("个人基本信息");
        findBaseView();
    }

    public void findBaseView() {
        imm= (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        click_head = (RelativeLayout) findViewById(R.id.click_head);
        click_phone = (RelativeLayout) findViewById(R.id.click_phone);
        click_get_address = (LinearLayout) findViewById(R.id.click_get_address);
        user_head = (ImageView) findViewById(R.id.user_head);
        user_name = (EditText) findViewById(R.id.user_name);
        user_nick = (EditText) findViewById(R.id.user_nick);
        user_compay_name = (TextView) findViewById(R.id.user_address_name);
        user_phone = (TextView) findViewById(R.id.user_phone);
        userNumber= (TextView) findViewById(R.id.userids);
        UserinfoModel  userInfo=(UserinfoModel)getIntent().getSerializableExtra("userinfo");
        user_address_name = (TextView) findViewById(R.id.user_get_address_name);
        home_send_order = (TextView) findViewById(R.id.home_send_order);
        if(userInfo!=null) {
            userNumber.setText(userInfo.getUserID()+"");
            if(userInfo.getNickname()!=null) {
                user_nick.setText(userInfo.getNickname());
                user_nick.setSelection(user_nick.getText().length());
            }
            if(userInfo.getUserName()!=null) {
                user_name.setText(userInfo.getUserName());
                user_name.setSelection(user_name.getText().length());
            }
            if(userInfo.getAddressCount()>0){
                user_address_name.setText("已设置收货地址");
            }else {
                user_address_name.setText("未设置收货地址");
            }
            if(userInfo.getCompanyName()!=null) {
                user_compay_name.setText(userInfo.getCompanyName());
            }
        }
        if (!(SharedPreferencesUtils.getSharedPreferences(Constant.userName, "") == null || SharedPreferencesUtils.getSharedPreferences(Constant.userName, "").equals(""))) {
            user_name.setText(SharedPreferencesUtils.getSharedPreferences(Constant.userName, ""));
        }
        if (!(SharedPreferencesUtils.getSharedPreferences(Constant.nickName, "") == null || SharedPreferencesUtils.getSharedPreferences(Constant.nickName, "").equals(""))) {
            user_nick.setText(SharedPreferencesUtils.getSharedPreferences(Constant.nickName, ""));
        }
        if (!(SharedPreferencesUtils.getSharedPreferences(Constant.phoneNum, "") == null || SharedPreferencesUtils.getSharedPreferences(Constant.phoneNum, "").equals(""))) {
            user_phone.setText(SharedPreferencesUtils.getSharedPreferences(Constant.phoneNum, ""));

        }
//        if (!(SharedPreferencesUtils.getSharedPreferences(Constant.address, "") == null || SharedPreferencesUtils.getSharedPreferences(Constant.userName, "").equals(""))) {
//            user_address_name.setText(SharedPreferencesUtils.getSharedPreferences(Constant.address, ""));
//        } else {
//            user_address_name.setText("未设置收获地址");
//        }
        if (!(SharedPreferencesUtils.getSharedPreferences(Constant.company, "") == null || SharedPreferencesUtils.getSharedPreferences(Constant.company, "").equals(""))) {
            user_compay_name.setText(SharedPreferencesUtils.getSharedPreferences(Constant.company, ""));
        }
        if (!(SharedPreferencesUtils.getSharedPreferences(Constant.face, "") == null || SharedPreferencesUtils.getSharedPreferences(Constant.face, "").equals(""))) {
            try {
                Glide.with(mContext).load(SharedPreferencesUtils.getSharedPreferences(Constant.face, "")).asBitmap().centerCrop().diskCacheStrategy(DiskCacheStrategy.ALL)
                        .transform(new CornersTransform(mContext))
                        .placeholder(R.mipmap.default_head)
                        .error(R.mipmap.default_head)
                        .into(new BitmapImageViewTarget(user_head) {
                            @Override
                            protected void setResource(Bitmap resource) {
                                RoundedBitmapDrawable circularBitmapDrawable =
                                        RoundedBitmapDrawableFactory.create(mContext.getResources(), resource);
                                circularBitmapDrawable.setCircular(true);
                                user_head.setImageDrawable(circularBitmapDrawable);
                            }
                        });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.click_head:
                new AlertView("上传头像", null, "取消", null,
                        new String[]{"拍照", "从相册中选择"},
                        this, AlertView.Style.ActionSheet, this).show();
                break;
            case R.id.click_phone:
                mAlertViewExt = new AlertView(null, null, "取消", null, new String[]{"确定"}, this, AlertView.Style.Alert, this);
                ViewGroup extView = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.alertext_form, null);
                etName = (EditText) extView.findViewById(R.id.etName);
                etName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                    @Override
                    public void onFocusChange(View view, boolean focus) {
                        //输入框出来则往上移动
                        boolean isOpen = imm.isActive();
                        mAlertViewExt.setMarginBottom(isOpen && focus ? 120 : 0);
                    }
                });
                mAlertViewExt.addExtView(extView);
                mAlertViewExt.show();
                break;
            case R.id.click_get_address:

                startActivityForResult(new Intent(this, ShopAddressActivity.class).putExtra("id", "5"), REQUEST_CODE_EDIT_ADDRESS);
                break;
            case R.id.home_send_order:
                name=user_name.getText().toString();
                nickname=user_nick.getText().toString();
                if(name.equals("")){
                    ToastUtil.toast(mContext,"请输入姓名");
                }else if(nickname.equals("")){
                    ToastUtil.toast(mContext,"请输入昵称");
                }else{
                    updateUser();
                }
                break;
        }
    }

    @Override
    public void onItemClick(Object o, int position) {
        //判断是否是拓展窗口View，而且点击的是非取消按钮
        if (o == mAlertViewExt && position != AlertView.CANCELPOSITION) {
            String name = etName.getText().toString();
            if (name.isEmpty()) {
                ToastUtil.toast(this, "请输入密码");
            } else {
                checkPass(name);

            }

            return;
        }
        if (position == 1) {
            CustomHelper.onClick(getTakePhoto(), position);
        } else if (position == 0) {
            CustomHelper.onClick(getTakePhoto(), position);
        }

    }

    @Override
    public void takeCancel() {
        super.takeCancel();
    }

    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
    }

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        Message msg = new Message();
        msg.obj = result.getImages();
        handler.sendMessage(msg);


    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            imgList = (ArrayList<TImage>) msg.obj;
            if (imgList != null) {
                try {
                    Glide.with(mContext).load(new File(imgList.get(0).getCompressPath())).asBitmap().centerCrop().diskCacheStrategy(DiskCacheStrategy.ALL)
                            .transform(new CornersTransform(mContext))
                            .placeholder(R.mipmap.default_head)
                            .error(R.mipmap.default_head)
                            .into(new BitmapImageViewTarget(user_head) {
                                @Override
                                protected void setResource(Bitmap resource) {
                                    RoundedBitmapDrawable circularBitmapDrawable =
                                            RoundedBitmapDrawableFactory.create(mContext.getResources(), resource);
                                    circularBitmapDrawable.setCircular(true);
                                    user_head.setImageDrawable(circularBitmapDrawable);
                                }
                            });
                    new UploadHelper().asyncPutObjectFromLocalFile(mContext, Constant.endpoint, imgList.get(0).getCompressPath(), new UploadCallback<Integer>() {
                        @Override
                        public void onRequestBefore() {

                        }

                        @Override
                        public void onFailure(PutObjectRequest response, String failureMsg, int code) {

                        }

                        @Override
                        public void onSuccess(PutObjectRequest response, Integer o) {
                              if(o==200){
                                  logo="https://"+Constant.testBucket + Constant.enp + "/" + response.getObjectKey();
                              }
                        }
                        @Override
                        public void onError(PutObjectRequest response, int errorCode, Exception e) {

                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
    };

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data != null) {
                final String returnData = data.getStringExtra("edit");
                switch (requestCode) {
                    case REQUEST_CODE_EDIT_ADDRESS: // 我的收货地址
                        user_address_name.setText("已设置收货地址");
                        break;
                    case REQUEST_CODE_EDIT_PHONE://手机号
                        user_phone.setText(returnData);
                        break;
                    default:
                        break;
                }
            }
        } else {
            return;
        }

    }

    public void updateUser() {
        try {
            Map<String, Object> parmas = new HashMap<>();
            parmas.put("device_type", Constant.device_type);
            parmas.put("token", SharedPreferencesUtils.getSharedPreferences(Constant.token, ""));
            JSONObject jsondata = new JSONObject();
            if(!(logo==null||logo.equals(""))) {
                jsondata.put("logo", logo);
            }
            if(!(name==null||name.equals(""))) {
                jsondata.put("name", name);
            }
            if(!(nickname==null||nickname.equals(""))){
                jsondata.put("nickname", nickname);
            }
            parmas.put("jsonText", jsondata.toString());
            MyService.userByIdUpdate(mContext, parmas, new ResponseCallback<UserinfoModel>() {
                @Override
                public void onSuccess(UserinfoModel userinfoModel) {
                          ToastUtil.toast(mContext,"操作成功");
                          finish();
                }

                @Override
                public void onError(Response response, int errorCode, String errorMsg, Exception e) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    public void checkPass(String oldPass) {
        try {
            Map<String, Object> parmas = new HashMap<>();
            parmas.put("device_type", Constant.device_type);
            parmas.put("token", SharedPreferencesUtils.getSharedPreferences(Constant.token, ""));
            JSONObject jsondata = new JSONObject();
            jsondata.put("oldPass", oldPass);
            try{
                InputStream inPublic = mContext.getResources().getAssets().open("rsa_public_key.pem");
                PublicKey publicKey = RSAUtils.loadPublicKey(inPublic);
                RSAUtils.printPublicKeyInfo(publicKey);
                // 加密
                byte[] encryptByte = RSAUtils.encryptData(jsondata.toString().getBytes(), publicKey);
                // 为了方便观察吧加密后的数据用base64加密转一下，要不然看起来是乱码,所以解密是也是要用Base64先转换
                String afterencrypt = Base64Utils.encode(encryptByte);
                parmas.put("jsonText", afterencrypt);
            }catch(Exception e){
                e.printStackTrace();
            }
            MyService.checkPass(mContext, parmas, new ResponseCallback<UserinfoModel>() {
                @Override
                public void onSuccess(UserinfoModel userinfoModel) {
                    startActivityForResult(new Intent(UserEditActivity.this, SetPhoneActivity.class).putExtra("id", "5").putExtra("name", user_phone.getText().toString().trim()), REQUEST_CODE_EDIT_PHONE);
                }

                @Override
                public void onError(Response response, int errorCode, String errorMsg, Exception e) {
                        ToastUtil.toast(mContext,"密码错误");
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
